package top.itmeans.yes.admin.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import top.itmeans.yes.admin.bo.AdminUserDetails;
import top.itmeans.yes.admin.service.AdminService;
import top.itmeans.yes.common.exception.Asserts;
import top.itmeans.yes.common.util.RequestUtil;
import top.itmeans.yes.dto.AdminParam;
import top.itmeans.yes.dto.UpdateAdminPasswordParam;
import top.itmeans.yes.entity.*;
import top.itmeans.yes.mapper.AdminLoginLogMapper;
import top.itmeans.yes.mapper.AdminMapper;
import top.itmeans.yes.mapper.AdminRoleRelationMapper;
import top.itmeans.yes.security.util.JwtTokenUtil;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 后台用户表 服务实现类
 * </p>
 *
 * @author Yiming.Cao
 * @since 2022-04-28
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {
    private static final Logger LOGGER = LoggerFactory.getLogger(AdminServiceImpl.class);

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private AdminRoleRelationMapper adminRoleRelationMapper;

    @javax.annotation.Resource(type = AdminLoginLogMapper.class)
    private AdminLoginLogMapper loginLogMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public Admin getAdminByUsername(String username) {
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Admin::getUsername,username);
        return adminMapper.selectOne(queryWrapper);
    }

    @Override
    public UserDetails loadUserByUsername(String username) {
        Admin admin = getAdminByUsername(username);
        if (admin != null) {
            List<Resource> resourceList = adminRoleRelationMapper.getResourceList(admin.getId());
            return new AdminUserDetails(admin,resourceList);
        }
        throw new UsernameNotFoundException("用户名或密码错误");
    }

    @Override
    public Admin register(AdminParam adminParam) {
        //查询是否有相同用户名的用户
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Admin::getUsername,adminParam.getUsername());
        if (adminMapper.selectCount(queryWrapper) > 0) {
            return null;
        }
        Admin admin = new Admin();
        BeanUtils.copyProperties(adminParam, admin);
        admin.setCreateTime(LocalDateTime.now());
        admin.setStatus(0);
        //将密码进行加密操作
        String encodePassword = passwordEncoder.encode(admin.getPassword());
        admin.setPassword(encodePassword);
        adminMapper.insert(admin);
        return admin;
    }

    @Override
    public String login(String username, String password) {
        String token = null;
        //密码需要客户端加密后传递
        try {
            UserDetails userDetails = loadUserByUsername(username);
            //加密，开发环境使用，生产环境去除
            //password = passwordEncoder.encode(password);
            if(!passwordEncoder.matches(password,userDetails.getPassword())){
                Asserts.fail("密码不正确");
            }
            if(!userDetails.isEnabled()){
                Asserts.fail("帐号已被禁用");
            }
            UsernamePasswordAuthenticationToken authentication =
                    new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            token = jwtTokenUtil.generateToken(userDetails);
            // updateLoginTimeByUsername(username);
            insertLoginLog(username);
        } catch (AuthenticationException e) {
            LOGGER.warn("登录异常:{}", e.getMessage());
        }
        return token;
    }

    @Override
    public String refreshToken(String oldToken) {
        return jwtTokenUtil.refreshHeadToken(oldToken);
    }

    @Override
    public List<Role> getRoleList(Long id) {
        return adminRoleRelationMapper.getRoleList(id);
    }

    @Override
    public Page<Admin> list(String keyword, Integer pageSize, Integer pageNum) {
        Page<Admin> adminPage = new Page<>(pageNum,pageSize);
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        if (!StrUtil.isEmpty(keyword)) {
            queryWrapper.like(Admin::getUsername,keyword)
                    .or()
                    .like(Admin::getNickName,keyword);
        }
        return adminMapper.selectPage(adminPage,queryWrapper);
    }

    @Override
    public int updatePassword(UpdateAdminPasswordParam param) {
        if(StrUtil.isEmpty(param.getUsername())
                ||StrUtil.isEmpty(param.getOldPassword())
                ||StrUtil.isEmpty(param.getNewPassword())){
            return -1;
        }
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Admin::getUsername,param.getUsername());
        List<Admin> adminList = adminMapper.selectList(queryWrapper);
        if(CollUtil.isEmpty(adminList)){
            return -2;
        }
        Admin admin = adminList.get(0);
        if(!passwordEncoder.matches(param.getOldPassword(),admin.getPassword())){
            return -3;
        }
        admin.setPassword(passwordEncoder.encode(param.getNewPassword()));
        adminMapper.updateById(admin);
        return 1;
    }

    @Override
    public int update(Long id, Admin admin) {
        admin.setId(id);
        Admin rawAdmin = adminMapper.selectById(id);
        if(rawAdmin.getPassword().equals(admin.getPassword())){
            //与原加密密码相同的不需要修改
            admin.setPassword(null);
        }else{
            //与原加密密码不同的需要加密修改
            if(StrUtil.isEmpty(admin.getPassword())){
                admin.setPassword(null);
            }else{
                admin.setPassword(passwordEncoder.encode(admin.getPassword()));
            }
        }
        return adminMapper.updateById(admin);
    }

    @Override
    public int updateRole(Long adminId, List<Long> roleIds) {
        int count =
                roleIds == null ? 0 : roleIds.size();
        //先删除原来的关系
        AdminRoleRelation adminRoleRelationExample = new AdminRoleRelation();
        adminRoleRelationExample.setId(adminId);
        adminRoleRelationMapper.deleteById(adminRoleRelationExample);
        //建立新关系
        if (!CollectionUtils.isEmpty(roleIds)) {
            for (Long roleId : roleIds) {
                AdminRoleRelation roleRelation = new AdminRoleRelation();
                roleRelation.setAdminId(adminId);
                roleRelation.setRoleId(roleId);
                adminRoleRelationMapper.insert(roleRelation);
            }
        }
        return count;
    }

    /**
     * 添加登录记录
     * @param username 用户名
     */
    private void insertLoginLog(String username) {
        Admin admin = getAdminByUsername(username);
        if(admin==null) {
            return;
        }
        AdminLoginLog loginLog = new AdminLoginLog();
        loginLog.setAdminId(admin.getId());
        loginLog.setCreateTime(LocalDateTime.now());
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        loginLog.setIp(RequestUtil.getRequestIp(request));
        loginLogMapper.insert(loginLog);
    }

    /**
     * 根据用户名修改登录时间
     */
    private void updateLoginTimeByUsername(String username) {
        LambdaUpdateWrapper<Admin> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Admin::getUsername,username);
        updateWrapper.set(Admin::getLoginTime,LocalDateTime.now());
        this.update(updateWrapper);
    }
}
